<template>
  <div class="labeler-task-package-page">
    <div class="page-header">
      <h2>提包领取以及完成情况</h2>
      <el-button type="primary" @click="showAddDialog">新增记录</el-button>
    </div>

    <!-- 查询条件 -->
    <div class="query-area">
      <el-form :model="queryForm" inline size="small">
        <el-form-item label="领取时间">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标注员姓名">
          <el-input
            v-model="queryForm.labelerName"
            placeholder="请输入标注员姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable>
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已返修" value="已返修"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="exportData">导出</el-button>
          <el-button @click="downloadTemplate">下载模板</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="tableLoading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column prop="labelerName" label="姓名" width="120" align="center"></el-table-column>
        <el-table-column prop="receiveTime" label="领取时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.receiveTime }}
          </template>
        </el-table-column>
        <el-table-column prop="account" label="账号" width="120" align="center"></el-table-column>
        <el-table-column prop="taskBatch" label="任务批次" width="120" align="center"></el-table-column>
        <el-table-column prop="packageId" label="提包Id" width="120" align="center"></el-table-column>
        <el-table-column prop="deliveryTime" label="交付时间" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.deliveryTime }}
          </template>
        </el-table-column>
        <el-table-column prop="deliveryBoxCount" label="交付框数" width="100" align="center"></el-table-column>
        <el-table-column prop="repairCount" label="返修次数" width="100" align="center"></el-table-column>
        <el-table-column prop="finalBoxCount" label="最终框数" width="100" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" style="color: #f56c6c" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        style="margin-top: 20px; text-align: right"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="packageForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="姓名" prop="labelerName">
          <el-input
            v-model="formData.labelerName"
            placeholder="请输入标注员姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="领取时间" prop="receiveTime">
          <el-date-picker
            v-model="formData.receiveTime"
            type="datetime"
            placeholder="请选择领取时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="账号" prop="account">
          <el-input
            v-model="formData.account"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>

        <el-form-item label="任务批次" prop="taskBatch">
          <el-input
            v-model="formData.taskBatch"
            placeholder="请输入任务批次"
          ></el-input>
        </el-form-item>

        <el-form-item label="提包Id" prop="packageId">
          <el-input
            v-model="formData.packageId"
            placeholder="请输入提包Id"
          ></el-input>
        </el-form-item>

        <el-form-item label="交付时间" prop="deliveryTime">
          <el-date-picker
            v-model="formData.deliveryTime"
            type="datetime"
            placeholder="请选择交付时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="交付框数" prop="deliveryBoxCount">
          <el-input-number
            v-model="formData.deliveryBoxCount"
            :min="0"
            placeholder="请输入交付框数"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="返修次数" prop="repairCount">
          <el-input-number
            v-model="formData.repairCount"
            :min="0"
            placeholder="请输入返修次数"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="最终框数" prop="finalBoxCount">
          <el-input-number
            v-model="formData.finalBoxCount"
            :min="0"
            placeholder="请输入最终框数"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="进行中" value="进行中"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已返修" value="已返修"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- Excel批量导入区域 -->
    <div class="batch-import-area">
      <div class="import-header">
        <h3>Excel批量导入</h3>
        <el-button type="primary" size="small" @click="downloadTemplate">
          <i class="el-icon-download"></i> 下载导入模板
        </el-button>
      </div>
      
      <el-upload
        class="upload-demo"
        drag
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="fileList"
        :limit="1"
        accept=".xlsx,.xls"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只支持.xlsx或.xls格式的Excel文件，文件大小不超过10MB</div>
      </el-upload>
      
      <!-- 文件预览区域 -->
      <div v-if="selectedFile" class="file-preview">
        <div class="preview-header">
          <i class="el-icon-document"></i>
          <span class="file-name">{{ selectedFile.name }}</span>
          <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
          <el-button 
            type="danger" 
            size="mini" 
            icon="el-icon-delete" 
            circle 
            @click="removeFile"
            title="删除文件"
          ></el-button>
        </div>
        <div class="preview-info">
          <p><i class="el-icon-info"></i> 文件已选择，点击"批量导入"按钮开始导入</p>
        </div>
      </div>
      
      <!-- 进度条 -->
      <el-progress 
        v-if="importLoading" 
        :percentage="importProgress" 
        :show-text="true" 
        style="margin-top: 10px;"
      ></el-progress>
      
      <el-button 
        type="success" 
        style="margin-top: 10px;" 
        @click="handleImport"
        :loading="importLoading"
        :disabled="!selectedFile"
      >
        <i class="el-icon-upload2"></i> {{ importLoading ? '导入中...' : '批量导入' }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { 
  getLabelerTaskPackageListAPI, 
  addLabelerTaskPackageAPI, 
  updateLabelerTaskPackageAPI, 
  deleteLabelerTaskPackageAPI,
  downloadTaskPackageTemplateAPI,
  importLabelerTaskPackageAPI,
  exportLabelerTaskPackageAPI
} from '@/api/labelerTaskPackage';

export default {
  name: 'LabelerTaskPackage',
  data() {
    return {
      dialogVisible: false,
      dialogTitle: '新增记录',
      submitLoading: false,
      // 查询表单
      queryForm: {
        dateRange: null,
        labelerName: '',
        status: ''
      },
      // 表格数据
      tableData: [],
      tableLoading: false,
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 表单数据
      formData: {
        labelerName: '',
        receiveTime: '',
        account: '',
        taskBatch: '',
        packageId: '',
        deliveryTime: '',
        deliveryBoxCount: 0,
        repairCount: 0,
        finalBoxCount: 0,
        status: '进行中'
      },
      formRules: {
        labelerName: [
          { required: true, message: '请输入标注员姓名', trigger: 'blur' }
        ],
        receiveTime: [
          { required: true, message: '请选择领取时间', trigger: 'change' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        taskBatch: [
          { required: true, message: '请输入任务批次', trigger: 'blur' }
        ],
        packageId: [
          { required: true, message: '请输入提包Id', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      // Excel导入相关
      selectedFile: null,
      fileList: [],  // 文件列表
      importLoading: false,
      importProgress: 0  // 导入进度
    };
  },
  mounted() {
    // 页面加载时查询数据
    this.getTableData();
  },
  methods: {
    // 查询数据
    handleQuery() {
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 重置查询
    handleReset() {
      this.queryForm = {
        dateRange: null,
        labelerName: '',
        status: ''
      };
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 导出数据
    exportData() {
      // 构建查询参数
      const params = {};
      
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.startDate = this.queryForm.dateRange[0];
        params.endDate = this.queryForm.dateRange[1];
      }
      
      if (this.queryForm.labelerName) {
        params.labelerName = this.queryForm.labelerName;
      }
      
      if (this.queryForm.status) {
        params.status = this.queryForm.status;
      }
      
      this.$message.info('正在导出数据，请稍候...');
      
      // 调用导出接口
      exportLabelerTaskPackageAPI(params).then(res => {
        if (res) {
          // 创建下载链接
          const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = '提包领取及完成情况.xlsx';
          link.click();
          window.URL.revokeObjectURL(url);
          this.$message.success('导出成功');
        } else {
          this.$message.error('导出失败');
        }
      }).catch(error => {
        this.$message.error('导出失败，请检查网络');
        console.error('导出错误:', error);
      });
    },
    
    // 下载模板
    downloadTemplate() {
      this.$message.info('正在下载模板...');
      downloadTaskPackageTemplateAPI().then(res => {
        // 创建下载链接
        const blob = new Blob([res], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = '提包领取及完成情况导入模板.xlsx';
        link.click();
        window.URL.revokeObjectURL(url);
        this.$message.success('模板下载成功');
      }).catch(error => {
        this.$message.error('模板下载失败');
        console.error('下载错误:', error);
      });
    },
    
    // 处理文件上传
    handleFileChange(file, fileList) {
      // 验证文件类型
      const isExcel = file.raw.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
                   || file.raw.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件！');
        // 移除非法文件
        this.fileList = [];
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB！');
        // 移除超大文件
        this.fileList = [];
        return false;
      }
      
      this.selectedFile = file.raw;
      this.fileList = [file];
    },
    
    // 删除文件（通过上传组件的删除按钮）
    handleFileRemove(file, fileList) {
      this.selectedFile = null;
      this.fileList = [];
      this.$message.info('文件已移除');
    },
    
    // 手动删除文件
    removeFile() {
      this.selectedFile = null;
      this.fileList = [];
      this.$message.info('文件已移除，可以重新上传');
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
    },
    
    // 批量导入
    handleImport() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择要导入的Excel文件');
        return;
      }
      
      this.importLoading = true;
      this.importProgress = 0;
      this.$message.info('正在导入数据，请稍候...');
      
      // 创建进度更新函数
      const updateProgress = (progressEvent) => {
        if (progressEvent.percent) {
          this.importProgress = Math.round(progressEvent.percent);
        }
      };
      
      importLabelerTaskPackageAPI(this.selectedFile, { onProgress: updateProgress }).then(res => {
        this.importLoading = false;
        if (res.code === 200) {
          // 更新导入结果数据
          const importResult = res.data || {
            totalRows: 0,
            successRows: 0,
            failRows: 0,
            errorMessages: []
          };
          
          // 根据导入结果给出相应提示
          if (importResult.failRows === 0) {
            this.$message.success(`导入完成！成功导入${importResult.successRows}条数据`);
          } else {
            this.$message.warning(`导入完成！成功${importResult.successRows}条，失败${importResult.failRows}条`);
          }
          
          // 导入成功后刷新列表
          this.getTableData();
          
          // 清空文件选择
          this.selectedFile = null;
          this.fileList = [];
        } else {
          this.$message.error(res.message || '导入失败');
        }
      }).catch(error => {
        this.importLoading = false;
        this.$message.error('导入失败，请检查网络或文件格式');
        console.error('导入错误:', error);
      });
    },
    
    // 获取状态标签类型
    getStatusTagType(status) {
      switch (status) {
        case '进行中':
          return 'primary';
        case '已完成':
          return 'success';
        case '已返修':
          return 'warning';
        default:
          return 'info';
      }
    },
    
    // 获取表格数据
    getTableData() {
      this.tableLoading = true;
      
      // 构建查询参数
      const params = {
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      };
      
      if (this.queryForm.dateRange && this.queryForm.dateRange.length === 2) {
        params.startDate = this.queryForm.dateRange[0];
        params.endDate = this.queryForm.dateRange[1];
      }
      
      if (this.queryForm.labelerName) {
        params.labelerName = this.queryForm.labelerName;
      }
      
      if (this.queryForm.status) {
        params.status = this.queryForm.status;
      }
      
      // 调用后端接口查询数据
      getLabelerTaskPackageListAPI(params).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.pagination.total = res.data.total || 0;
          this.pagination.currentPage = res.data.currentPage || 1;
          this.pagination.pageSize = res.data.pageSize || 10;
        } else {
          this.$message.error(res.message || '查询失败');
        }
      }).catch(error => {
        this.tableLoading = false;
        this.$message.error('查询失败，请检查网络');
        console.error('查询错误:', error);
      });
    },
    
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑记录';
      this.formData = { ...row };
      this.dialogVisible = true;
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用后端删除接口
        deleteLabelerTaskPackageAPI(row.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getTableData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        }).catch(error => {
          this.$message.error('删除失败，请检查网络');
          console.error('删除错误:', error);
        });
      }).catch(() => {});
    },
    
    // 分页 - 每页条数改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getTableData();
    },
    
    // 分页 - 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getTableData();
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.dialogTitle = '新增记录';
      this.resetForm();
      this.dialogVisible = true;
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        labelerName: '',
        receiveTime: '',
        account: '',
        taskBatch: '',
        packageId: '',
        deliveryTime: '',
        deliveryBoxCount: 0,
        repairCount: 0,
        finalBoxCount: 0,
        status: '进行中'
      };
      if (this.$refs.packageForm) {
        this.$refs.packageForm.resetFields();
      }
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.packageForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          
          // 判断是新增还是编辑
          const isEdit = !!this.formData.id;
          const apiCall = isEdit 
            ? updateLabelerTaskPackageAPI(this.formData.id, this.formData)
            : addLabelerTaskPackageAPI(this.formData);
          
          apiCall.then(res => {
            this.submitLoading = false;
            if (res.code === 200) {
              this.$message.success(isEdit ? '修改成功' : '新增成功');
              this.dialogVisible = false;
              this.resetForm();
              // 刷新列表
              this.getTableData();
            } else {
              this.$message.error(res.message || '操作失败');
            }
          }).catch(error => {
            this.submitLoading = false;
            this.$message.error('操作失败，请检查网络');
            console.error('提交错误:', error);
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.labeler-task-package-page {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }
  
  .batch-import-area {
    margin-top: 40px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
    
    .import-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #333;
    }
    
    .upload-demo {
      width: 100%;
    }
    
    .file-preview {
      margin-top: 15px;
      padding: 15px;
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      .preview-header {
        display: flex;
        align-items: center;
        gap: 10px;
        
        i.el-icon-document {
          font-size: 24px;
          color: #67c23a;
        }
        
        .file-name {
          flex: 1;
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .file-size {
          font-size: 12px;
          color: #909399;
        }
      }
      
      .preview-info {
        margin-top: 10px;
        padding: 8px 12px;
        background: #ecf5ff;
        border-left: 3px solid #409eff;
        border-radius: 4px;
        
        p {
          margin: 0;
          font-size: 13px;
          color: #409eff;
          
          i {
            margin-right: 5px;
          }
        }
      }
    }
  }
}
</style>